package org.ling.xuan.dao;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import org.ling.xuan.entity.AddInfoContext;
import org.ling.xuan.entity.mo.CommonSetting;
import org.ling.xuan.entity.mo.EmailSetting;
import org.ling.xuan.util.LxIoUtil;

import java.io.File;
import java.nio.charset.StandardCharsets;

public class FileDao {

    private static final String fileRoot = LxIoUtil.getWorkHome() + "/.lx/file";

    public static <T> T get(Class<T> tClass, String fileName, T defaultT) {
        File file = new File(fileRoot + "/" + fileName);
        String s = "";
        if (file.exists()) {
            s = FileUtil.readUtf8String(fileRoot + "/" + fileName);
        }
    
        if (StrUtil.isNotBlank(s)) {
            try {
                return com.alibaba.fastjson.JSONObject.parseObject(s,tClass);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("反序列化失败");
            }
        }
        return defaultT;
    }

    public static <T> void update(T t, String fileName) {
        try {
            File file = new File(fileRoot + "/" + fileName);
            if (!file.exists()) {
                FileUtil.mkParentDirs(fileRoot + "/" + fileName);
                file.createNewFile();
            }
            String s = com.alibaba.fastjson.JSONObject.toJSONString(t);
            FileUtil.writeString(s, fileRoot + "/" + fileName, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("反序列化失败");
        }
    }

    public static CommonSetting getCommonSetting() {
        return FileDao.get(CommonSetting.class, "CommonSetting.json", new CommonSetting());
    }

    public static EmailSetting getEmailSetting() {
        return FileDao.get(EmailSetting.class, "EmailSetting.json", new EmailSetting());
    }

    public static void writeAddInfoContext(AddInfoContext addInfoContext, String od) {
        addInfoContext.setId(od);
        String root = LxIoUtil.getWorkHome()+ "/.lx/add/" + od;
        addInfoContext.setRootPath(root);
        String addInfoFile = root + "/" + "addInfo.json";
        FileUtil.writeString(com.alibaba.fastjson.JSONObject.toJSONString(addInfoContext),addInfoFile,StandardCharsets.UTF_8);
    }

    public static AddInfoContext  getAddInfoContext(String od) {
        String root = LxIoUtil.getWorkHome() + "/.lx/add/" + od;
        String addInfoFile = root + "/" + "addInfo.json";
        if(FileUtil.exist(addInfoFile)) {
            return com.alibaba.fastjson.JSONObject.parseObject(FileUtil.readUtf8String(addInfoFile),AddInfoContext.class);
        }else{
            return new AddInfoContext();
        }
    }
}
